
import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosError
} from 'axios'
import qs from 'qs'

import { message } from 'ant-design-vue';
import router, { resetRouter } from '@/router/index'
import { useAppStoreFn } from "@/store/modules/app"
import { useCache } from "@/hooks/useCache"

import { isObjectEmpty } from "@/utils/index"
import { HTTP_NOTOKEN_CODE, HTTP_SUCCESS_CODE, AXIOS_UNTOKEN_API } from "@/config/vars"

const { wsCache } = useCache()

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: "https://rlzy.hnnxdbgs.com/api", // api 的 base_url
  timeout: 60000 // 请求超时时间 60秒
})

const isGet = (config: AxiosRequestConfig) => {
  return config.method === 'get'
}
const isPost = (config: AxiosRequestConfig) => {
  return config.method === 'post'
}
const isUrlencoded = (config: AxiosRequestConfig) => {
  if (config && config.headers && config.headers['Content-Type']) {
    let contentType = config.headers['Content-Type'];
    return contentType == 'application/x-www-form-urlencoded'
  }
}

let responseType: string;

// request拦截器
service.interceptors.request.use(
  (config) => {
    const appStore = useAppStoreFn()
    const token = wsCache.get(appStore.getToken)
    responseType = config && config.responseType ? config.responseType : '';
    // 存在token，且不在不需要token的接口列表中 则在header中加入token
    if (AXIOS_UNTOKEN_API.indexOf(config.url as string) == -1 && token != undefined) {
      config.headers['Authorization'] = token;
    }

    if (isPost(config) && isUrlencoded(config)) {
      config.data = qs.stringify(config.data)
    }
    // get参数编码
    if (isGet(config) && !isObjectEmpty(config.params)) {
      let url = config.url as string
      url += '?'
      const keys = Object.keys(config.params)
      for (const key of keys) {
        if (config.params[key] !== void 0 && config.params[key] !== null) {
          url += `${key}=${encodeURIComponent(config.params[key])}&`
        }
      }
      url = url.substring(0, url.length - 1)
      config.params = {}
      config.url = url
    }
    return config
  },
  (error: AxiosError) => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  (response) => {

    //返回值类型为文档流
    if (responseType == 'blob') {
      if (response.status == HTTP_SUCCESS_CODE) {
        return response
      } else {
        message.error("文件下载失败")
      }
    } else {
      const errorMessage = response.data.message || response.data.msg || "访问出错";
      if (response.data.code === '0' && response.status === HTTP_SUCCESS_CODE) {
        return response.data
      } else if (response.data.code == HTTP_NOTOKEN_CODE) {
        // 401 接口验证失败
        message.error(errorMessage);
        // 清除本地缓存
        wsCache.clear()
        resetRouter() // 重置静态路由表
        setTimeout(() => {
          // 没有Token跳转回云平台
          window.location.href = import.meta.env.VITE_APP_CLOUD_URL;
        }, 1500);
      } else {
        message.error(errorMessage);
      }
    }
  },
  (error: AxiosError) => {
    console.log('err' + error) // for debug
    message.error(error.message);
    return Promise.reject(error)
  }
)

export { service }